package com.spring.springboot.config;

import javax.sql.DataSource;

import org.quartz.ScheduleBuilder;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
*@author LSY
*Time: 2018年12月21日上午9:26:29
*
*
*/
@Configuration
@EnableScheduling
public class QueryzConfiguration {

	public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements 
	ApplicationContextAware{

		private transient AutowireCapableBeanFactory beanFactory;
		@Override
		public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
			beanFactory = applicationContext.getAutowireCapableBeanFactory();
			
		}
		
		@Override
		protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
			final Object job = super.createJobInstance(bundle);
			beanFactory.autowireBean(job);
			return job;
		}
		
	}
	
	@Bean
	public JobFactory jobFactory(ApplicationContext applicationContext) {
		AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
		jobFactory.setApplicationContext(applicationContext);
		return jobFactory;
	}
	
	@Bean(destroyMethod = "destroy", autowire = Autowire.NO)
	public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) {
		
		SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
		//将spring管理的job交给调度器
		factoryBean.setJobFactory(jobFactory);
		//覆盖已经存在的任务
		factoryBean.setOverwriteExistingJobs(true);
		//项目启动完成后，等待2秒后开始执行调度器初始化
		factoryBean.setStartupDelay(2);
		//使用调度器自动启动
		factoryBean.setAutoStartup(true);
		
		factoryBean.setDataSource(dataSource);
		//设置上下文
		factoryBean.setApplicationContextSchedulerContextKey("applicationContext");
		//设置配置文件位置
		factoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
		return factoryBean;
	}
}
